/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.teamreinforce.web.controllers;

import com.teamreinforce.logic.beans.CollaborateurFacade;
import com.teamreinforce.logic.beans.NotificationFacade;
import com.teamreinforce.logic.beans.ProjetFacade;
import com.teamreinforce.logic.beans.ReponseFacade;
import com.teamreinforce.logic.beans.SujetFacade;
import com.teamreinforce.logic.beans.TacheFacade;
import com.teamreinforce.logic.entities.*;
import com.teamreinforce.logic.model.IModel;
import com.teamreinforce.utils.TeamReinforceTimeUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author tidiane
 */
@WebServlet(
                name = "ControllerServlet", 
                loadOnStartup = 1,
                urlPatterns = 
                                {
                                    "/login",
                                    "/logout",
                                    "/projets",
                                    "/taches",
                                    "/forum",
                                    "/les-forums",
                                    "/discutions",
                                    "/cleannotifications",
                                    "/tableaudebord",
                                    "/reunions",
                                    "/details",
                                    "/task-details",
                                    "/delete-notifs"
                                }
            )
public class ControllerServlet extends HttpServlet {

    /**
     * The session beans injection
     */

    /** 
     * Processes requests for both HTTP <code> GET </code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    @EJB
    private CollaborateurFacade collaborateurF;
    
    @EJB
    private ProjetFacade projetF;
    
    @EJB
    private TacheFacade tacheF;
    
    @EJB
    private NotificationFacade notificationF;
    
    @EJB
    private SujetFacade sujetF;
    
    @EJB
    private ReponseFacade reponseF;
    
    @EJB
    private IModel model;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int pid = Integer.parseInt(request.getParameter("pid").toString());
        Projet projet = projetF.find(pid);
        
        int rest = 0;
        rest = TeamReinforceTimeUtils.calculateDuration(TeamReinforceTimeUtils.DATE, projet.getDateFin());
        
        String _rest = Integer.toString(pid);
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
 
            out.println("<form class=\"form-horizontal\"><fieldset>");
                out.println("<div class=\"control-group\">");
                    out.println("<label class = \"control-label\" > Projet  </label>");
                    out.println("<div class = \"controls\">");
                        out.println("<input type = \"text\" value = \""+ projet.getTitre() +"\" class = \"input-xlarge uneditable-input\">");
                    out.println("</div>");
                out.println("</div>");

                out.println("<div class = \"control-group\">");
                    out.println("<label class = \"control-label\" > Description  </label>");
                    out.println("<div class= \"controls\">");
                        out.println("<textarea class =\"input-xlarge uneditable-textarea\" style= \"height: 100px;\"> " + projet.getDescription() + " </textarea>");
                    out.println("</div>");
                out.println("</div>");

                out.println("<div class=\"control-group\">");
                    out.println("<label class = \"control-label\" > Date de début </label>");
                    out.println("<div class = \"controls\">");
                        out.println("<input type = \"text\" value = \"" + projet.getDateDebut() + "\" class = \"input-medium uneditable-input\">");
                    out.println("</div>");
                out.println("</div>");

                out.println("<div class = \"control-group\">");
                    out.println("<label class = \"control-label\" > Effectif </label>");
                    out.println("<div class = \"controls\">");
                        out.println("<input type = \"button\" value = \"" + projet.getRoleList().size() +" personnes\" class = \"input-mini btn-small\" >");
                    out.println("</div>");
                out.println("</div>");

                out.println("<div class = \"control-group\">");
                    out.println("<label class = \"control-label\" > Jours restant </label>");
                    out.println("<div class = \"controls\">");
                    
                    String classStr = "class = \"input-mini btn-small btn-success\"";
                    // Le quart du projet est atteint  
                    if ( rest <=  projet.getDuree() / 4 ) 
                    {
                        classStr = "class = \"input-mini btn-small btn-danger\"";
                        
                    }
                    _rest = Integer.toString(pid);
                    if (rest < 0) {
                        _rest = "dépassement de " + (-rest);
                    }
                    
                        out.println("<input type = \"button\" value = \"" + _rest + " jours\" " + classStr + " >");
                    out.println("</div>");
                out.println("</div>");

            out.println("</fieldset></form>");
        } finally {              
            out.close();
        }
    }

    /**
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException 
     */
    protected void processTaskDetails(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int tid = Integer.parseInt(request.getParameter("tid").toString());
        Tache tache = tacheF.find(tid);
        
        int rest = 0;
        rest = TeamReinforceTimeUtils.calculateDuration(TeamReinforceTimeUtils.DATE, tache.getDateFin());
        String _rest = Integer.toString(rest);
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
         
        try {
 
            out.println("<form class=\"form-horizontal\"><fieldset>");
                out.println("<div class=\"control-group\">");
                    out.println("<label class = \"control-label\" > Projet  </label>");
                    out.println("<div class = \"controls\">");
                        out.println("<input type = \"text\" value = \""+ tache.getLibelle() +"\" class = \"input-xlarge uneditable-input\">");
                    out.println("</div>");
                out.println("</div>");

                out.println("<div class = \"control-group\">");
                    out.println("<label class = \"control-label\" > Description  </label>");
                    out.println("<div class= \"controls\">");
                        out.println("<textarea class =\"input-xlarge uneditable-textarea\" style= \"height: 100px;\"> " + tache.getDescription() + " </textarea>");
                    out.println("</div>");
                out.println("</div>");

                out.println("<div class=\"control-group\">");
                    out.println("<label class = \"control-label\" > Date de début </label>");
                    out.println("<div class = \"controls\">");
                        out.println("<input type = \"text\" value = \"" + tache.getDateDebut() + "\" class = \"input-medium uneditable-input\">");
                    out.println("</div>");
                out.println("</div>");

                out.println("<div class = \"control-group\">");
                    out.println("<label class = \"control-label\" > Collaborateur (s) </label>");
                    out.println("<div class = \"controls\">");
                        for ( Collaborateur c : tache.getCollaborateurList()){
                            out.println("<input type = \"button\" value = \"" + c.getLogin() + "\" class = \"input-mini btn-small\" >");
                        }
                    out.println("</div>");
                out.println("</div>");

                out.println("<div class = \"control-group\">");
                    out.println("<label class = \"control-label\" > Jours restant </label>");
                    out.println("<div class = \"controls\">");
                    
                    String classStr = "class = \"input-mini btn-small btn-success\"";
                    // Le quart du projet est atteint  
                    if ( rest <=  tache.getDuree() / 4 ) 
                    {
                        classStr = "class = \"input-mini btn-small btn-danger\"";
                    }
                    
                    _rest = Integer.toString(rest);
                    
                    if ( rest < 0 ){
                        _rest = "dépassement de " + (-rest);
                    }
                        out.println("<input type = \"button\" value = \"" + _rest + " jours\" " + classStr + " >");
                    out.println("</div>");
                out.println("</div>");

            out.println("</fieldset></form>");
        } finally {             
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specifirequestc error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String url = request.getServletPath();
        /**
         * See the projects
         */
        
        if ( url.equals("/projets")) {
            getServletContext().setAttribute("target", "mes-projets");
            request.getRequestDispatcher("user.jsp").forward(request, response);
        }
        
        /**
         * Tasks
         */
        if ( url.equals("/taches")) {
            HttpSession session = request.getSession(false);
            if ( session != null){

                String uid = session.getAttribute("user").toString();
                int pid    = Integer.parseInt(request.getParameter("pid"));
                
                Collaborateur user = collaborateurF.find(Integer.parseInt(uid));
                
                List<Tache> taches = user.getTacheList();

                for ( Tache t : taches ) {
                    Projet projet = t.getEtape().getProjet();
                    if ( projet.getIdProjet() != pid) {
                        taches.remove(t);
                    }
                }

                request.setAttribute("pid", pid);
                session.setAttribute("pid", pid);
                getServletContext().setAttribute("projet", projetF.find(pid));
                getServletContext().setAttribute("ntaches", taches.size());
                getServletContext().setAttribute("taches", taches);
                getServletContext().setAttribute("target", "mes-taches");
                request.getRequestDispatcher("user.jsp").forward(request, response);
            }
            else  {
                System.err.println(" Pas bien !!! ");
            }
        }

        /**
         * Get
         */
        if (url.equals("/delete-notifs")) {
            HttpSession session = request.getSession(false);
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            if ( session != null ){
                try{
                    int uid = Integer.parseInt(session.getAttribute("user").toString());
                    Collaborateur user = collaborateurF.find(uid);

                    for ( Notification n : user.getNotificationList()) {
                        notificationF.remove(n);
                    }
                    user.getNotificationList().clear();
                    collaborateurF.edit(user);
                    session.setAttribute("notifications", user.getNotificationList());
                    session.setAttribute("nnotifications", 0);
                    
                }catch (Exception e){
                    e.printStackTrace();
                }
            System.out.println("C bon !! ");
            }
        }
        
        /**
         * Give the particular forum
         */
        if ( url.equals("/forum")) {
            HttpSession session = request.getSession(false);
            
            if ( session != null ){
                int pid = Integer.parseInt(session.getAttribute("pid").toString());
                Projet projet = projetF.find(pid);
                
                List <Sujet> _sujets = projet.getSujetList();
                getServletContext().setAttribute("sujets", _sujets);
                getServletContext().setAttribute("target", "forum");
                request.getRequestDispatcher("user.jsp").forward(request, response);
            }
        } 
        
        // les forum
        if ( url.equals("/les-forums")) {
                getServletContext().setAttribute("projets", projetF.findAll());
                getServletContext().setAttribute("target", "les-forums");
                request.getRequestDispatcher("user.jsp").forward(request, response);
        }
        /**
         * Discussions
         */
        if ( url.equals("/discutions")) {
            int sid = Integer.parseInt(request.getParameter("sid").toString());
            Sujet _sujet = sujetF.find(sid);
            getServletContext().setAttribute("titre", _sujet.getTitre());
            getServletContext().setAttribute("sujet", _sujet.getSujet());
            getServletContext().setAttribute("sujetObj", _sujet);
            getServletContext().setAttribute("target", "discutions");
            request.getRequestDispatcher("user.jsp").forward(request, response);
        }
        
        /**
         * Dashbord
         */
        if ( url.equals("/tableaudebord")) {
            // TODO : Some logic code here
            getServletContext().setAttribute("target", "dashbord");
            request.getRequestDispatcher("user.jsp").forward(request, response);
        }

        /**
         * Logging out the user !
         * Clean the notifications properly
         */
        if ( url.equals("/logout")) {
            HttpSession session = request.getSession(false);
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            if ( session != null ){
                try{
                    int uid = Integer.parseInt(session.getAttribute("user").toString());
                    Collaborateur user = collaborateurF.find(uid);
//
//                    for ( Notification n : user.getNotificationList()) {
//                        notificationF.remove(n);
//                    }
//                    
                    // terminate the session
                    session.invalidate();
                    out.println(" Déconnexion du système Teamreinforce !");
                    out.close();
                    
                }catch (Exception e) {
                    e.printStackTrace();
                    out.println(" Error lors de la déconnexion. \n Message : " + e.getMessage());
                    out.close();
                }
            }
        }
        
        // the meeting 
        if ( url.equals("/reunions")) {
            // Getting the user
            HttpSession session = request.getSession(false);
            if ( session != null ){
                int uid = Integer.parseInt(session.getAttribute("user").toString());
                Collaborateur find = collaborateurF.find(uid);
                getServletContext().setAttribute("collobarateur", find);
                
                getServletContext().setAttribute("target", "reunions");
                request.getRequestDispatcher("user.jsp").forward(request, response);
            }
        }
        
        /**
         * Getting project details by AJAX
         */
        if ( url.equals("/details")) {
            // redirect to the process method
            processRequest(request, response);
        }
        
        /**
         * Get task details
         * 
         */
        if ( url.equals("/task-details")) {
            processTaskDetails(request, response);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.projet
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String url = request.getServletPath();
        
        if ( url.equals("/login")) {
            // TODO : Login logic here
            String login = request.getParameter("login");
            String password = request.getParameter("password");

            try {
                HttpSession session = request.getSession(false);
                if ( session != null ) {
                    int uid = model.login(login, password);
                    
                    if ( uid != -1 ) {
                        Collaborateur user = collaborateurF.find(uid);
                        session.setAttribute("user", uid);
                        session.setAttribute("login", login);
                        session.setAttribute("nnotifications", user.getNotificationList().size());
                        session.setAttribute("notifications", user.getNotificationList());
                        List<Role> roles = user.getRoleList();
                        session.setAttribute("roles", roles);
                        
                        getServletContext().setAttribute("userObj", user);
                        getServletContext().setAttribute("target", "mes-projets");
                        request.getRequestDispatcher("user.jsp").forward(request, response);
                    }else{
                        request.getRequestDispatcher("error.jsp").forward(request, response);
                    }
                } else {
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                }
            }catch (Exception e) {
                request.getRequestDispatcher("index.jsp").forward(request, response);
            } 
        }
        
        /**
         * Set the avancement of the task
         */
        if ( url.equals("/taches")) {
            HttpSession session = request.getSession(false);
            
            String tid = request.getParameter("tid");
            int avancement = Integer.parseInt(request.getParameter("avancement"));
            
            if ( session != null) {
                // Setting the avancement
                Tache task = tacheF.find(Integer.parseInt(tid));
                task.setAvancement(avancement);
                
                //Save
                tacheF.edit(task);
                
                String uid = session.getAttribute("user").toString();
                int pid    = Integer.parseInt(request.getParameter("pid"));
                
                Collaborateur user = collaborateurF.find(Integer.parseInt(uid));
                
                List<Tache> taches = user.getTacheList();
                
                for ( Tache t : taches ) {
                    Projet projet = t.getEtape().getProjet();
                    if ( projet.getIdProjet() != pid) {
                        taches.remove(t);
                    }
                }
                
                getServletContext().setAttribute("ntaches", taches.size());
                getServletContext().setAttribute("taches", taches);
                getServletContext().setAttribute("target", "mes-taches");

                request.getRequestDispatcher("user.jsp").forward(request, response);   
            }else {
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }
        }
        
        /**
         * The forum 
         */
        if ( url.equals("/forum"))  {
            HttpSession session = request.getSession(false);
            
            if ( session != null) {

                int pid = Integer.parseInt(session.getAttribute("pid").toString());
                Projet projet = projetF.find(pid);
                
                int uid = Integer.parseInt(session.getAttribute("user").toString());
                Collaborateur collaborateur = collaborateurF.find(uid);
                
                // Getting informations
                String titre = request.getParameter("titre");
                String description = request.getParameter("description");
                
                Sujet sujet = new Sujet(Integer.MIN_VALUE, titre, description, TeamReinforceTimeUtils.DATE + " à " + TeamReinforceTimeUtils.TIME);
                sujet.setProjet(projet);
                sujet.setCollaborateur(collaborateur);
                
                sujetF.create(sujet);
                projet.getSujetList().add(sujet);
                projetF.edit(projet);
                
                List <Sujet> _sujets = projet.getSujetList();
                
                getServletContext().setAttribute("projet", projet);
                getServletContext().setAttribute("sujets", _sujets);
                
                getServletContext().setAttribute("target", "forum");

                request.getRequestDispatcher("user.jsp").forward(request, response); 
            }
            else {
                request.getRequestDispatcher("index.jsp").forward(request, response); 
            }
        }
        
        /**
         * Post a new response
         */
        if ( url.equals("/discutions")) {
            HttpSession session = request.getSession(false);
            if ( session != null) {
                
                int sid = Integer.parseInt(request.getParameter("sid").toString());
                Sujet _sujet = sujetF.find(sid);
                
                int uid = Integer.parseInt(session.getAttribute("user").toString());
                Collaborateur collaborateur = collaborateurF.find(uid);
                
                // Getting informations
                String message = request.getParameter("response");
                
                Reponse _rps = new Reponse(Integer.MAX_VALUE, message, TeamReinforceTimeUtils.DATE + " à " + TeamReinforceTimeUtils.TIME);

                _rps.setSujet(_sujet);
                _rps.setCollaborateur(collaborateur);

                reponseF.create(_rps); 
                _sujet.getReponseList().add(_rps);
                sujetF.edit(_sujet);
                collaborateurF.edit(collaborateur);

                List<Reponse> reponseList = _sujet.getReponseList();
                
                getServletContext().setAttribute("titre", _sujet.getTitre());
                getServletContext().setAttribute("sujet", _sujet.getSujet());
                getServletContext().setAttribute("sid", _sujet.getIdSujet());
                getServletContext().setAttribute("sujetObj", _sujet);
                
                getServletContext().setAttribute("sid", sid);
                
                getServletContext().setAttribute("target", "discutions");
                
                request.getRequestDispatcher("user.jsp").forward(request, response); 
            } 
            else {
                request.getRequestDispatcher("index.jsp").forward(request, response); 
            }
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
